package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysMenu;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @Author YuBaoFu
 * @create 2025/05/28
 * @description
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> menuList = sysMenuDao.findObjects();
        if (menuList==null || menuList.size()==0){
            throw new ServiceException("没有对应的菜单信息");
        }
        return menuList;
    }

    @Override
    public int deleteObjects(Integer id) {

        //1.验证数据的合法性
        if(id==null||id<=0)
            throw new IllegalArgumentException("请先选择");
        //2.基于id进行子元素查询
        int count=sysMenuDao.getChildCount(id);
        if(count>0)
            throw new ServiceException("请先删除子菜单");
        //3.删除角色,菜单关系数据
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        //4.删除菜单元素
        int rows=sysMenuDao.deleteObject(id);
        if(rows==0)
            throw new ServiceException("此菜单可能已经不存在");
        //5.返回结果
        return rows;

    }

    @Override
    public List<Node> findZTreeMenuNodes() {
        return sysMenuDao.findZTreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu sysMenu) {

        if (sysMenu == null){
            throw new ServiceException("保存菜单对象不可为空~");
        }
        if (!StringUtils.hasLength(sysMenu.getName())){
            throw new ServiceException("保存的菜单名不可为空~");
        }
        sysMenu.setCreatedUser("王鹏力");
        int rows = sysMenuDao.saveObject(sysMenu);
        if (rows == 0){
            throw new ServiceException("保存失败，请稍后重试~ /(ㄒoㄒ)/~~");
        }
        return rows;
    }

    @Override
    public void updateObject(SysMenu sysMenu) {
        //1.合法验证
        if(sysMenu==null)
            throw new ServiceException("保存对象不能为空");
        if(!StringUtils.hasLength(sysMenu.getName()))
            throw new ServiceException("菜单名不能为空");

        //2.更新数据
        sysMenu.setModifiedUser("王鹏力");
        int rows=sysMenuDao.updateObject(sysMenu);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //3.返回数据
    }
}
